/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iceberg.adgt.ui;

import com.iceberg.adgt.common.Observer;
import com.iceberg.adgt.common.ObserverInterest;
import com.iceberg.adgt.common.ObserverInterestMap;
import com.iceberg.adgt.io.FileOpener;
import com.iceberg.adgt.io.Writer;
import com.iceberg.adgt.io.XMLWriter;

import java.io.File;

/**
 * @author David
 */
public final class ADGTControllerImpl implements ADGTController {

	private final FileOpener fo = new FileOpener();
	private final Writer writer = new XMLWriter();
	private final ObserverInterestMap oim = new ObserverInterestMap();
	private File currentArchitectureFile;
	private File currentStructureFile;

	@Override
	public void openArchitectureFile(File file) {
		fo.openArchitectureFile(file);
		currentArchitectureFile = file;
		oim.notifyObservers(ObserverInterest.ARCHITECTURE_FILE_OPENED);
	}

	@Override
	public void openStructureFile(File file) {
		fo.openStructureFile(file);
		currentStructureFile = file;
		oim.notifyObservers(ObserverInterest.STRUCTURE_FILE_OPENED);
	}

	@Override
	public void save() {
		if (this.currentArchitectureFile != null && this.currentStructureFile != null) {
			writer.writeArchitectureFile(this.currentArchitectureFile);
			writer.writeStructureFile(this.currentStructureFile);
		}
	}

	@Override
	public void saveAs(File file) {
		File structureFile;

		if (!file.getPath().endsWith(".xml")) {
			currentArchitectureFile = new File(file.getPath() + ".xml");

			String[] fileSplits = this.currentArchitectureFile.getPath().split("\\.");
			structureFile = new File(fileSplits[0] + "_structure.xml");

			this.currentStructureFile = structureFile;

			save();
		}
	}

	@Override
	public String getCurrentArchitectureFileName() {
		return currentArchitectureFile.getName();
	}

	@Override
	public String getCurrentStructureFileName() {
		return currentStructureFile.getName();
	}

	@Override
	public void addObserver(Observer observer, ObserverInterest interest) {
		oim.put(interest, observer);
	}

}
